package com.newly.common.core.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.newly.common.base.constants.AuthConstant;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gjm guan
 * @date 2021/9/1 17:12
 * @desc 公共工具类
 */
public class NewlyCommonUtils {
    private static Snowflake snowflake = null;

    /**
     * 获取操作系统信息
     *
     * @param userAgent 请求头源数据
     * @return 操作系统字符串数据
     */
    public static String getOperationSystem(String userAgent) {
        if (StrUtil.isBlank(userAgent))
            return null;
        String user = userAgent.toLowerCase();
        String os = "";
        //=================OS Info=======================
        if (userAgent.toLowerCase().indexOf("windows") >= 0) {
            os = "Windows";
        } else if (userAgent.toLowerCase().indexOf("mac") >= 0) {
            os = "Mac";
        } else if (userAgent.toLowerCase().indexOf("x11") >= 0) {
            os = "Unix";
        } else if (userAgent.toLowerCase().indexOf("android") >= 0) {
            os = "Android";
        } else if (userAgent.toLowerCase().indexOf("iphone") >= 0) {
            os = "IPhone";
        } else {
            os = "UnKnown, More-Info: " + userAgent;
        }
        return os;
    }

    /**
     * 获取浏览器信息
     *
     * @param userAgent 请求头源数据
     * @return 浏览器字符串数据
     */
    public static String getBrowseInfo(String userAgent) {
        if (StrUtil.isBlank(userAgent))
            return null;
        String user = userAgent.toLowerCase();
        String browser = "";
        if (user.contains("edge")) {
            browser = (userAgent.substring(userAgent.indexOf("Edge")).split(" ")[0]).replace("/", "-");
        } else if (user.contains("msie")) {
            String substring = userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
            browser = substring.split(" ")[0].replace("MSIE", "IE") + "-" + substring.split(" ")[1];
        } else if (user.contains("safari") && user.contains("version")) {
            browser = (userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0]
                    + "-" + (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
        } else if (user.contains("opr") || user.contains("opera")) {
            if (user.contains("opera")) {
                browser = (userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split("/")[0]
                        + "-" + (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1];
            } else if (user.contains("opr")) {
                browser = ((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-"))
                        .replace("OPR", "Opera");
            }

        } else if (user.contains("chrome")) {
            browser = (userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0]).replace("/", "-");
        } else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1) ||
                (user.indexOf("mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1) ||
                (user.indexOf("mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1)) {
            browser = "Netscape-?";

        } else if (user.contains("firefox")) {
            browser = (userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-");
        } else if (user.contains("rv")) {
            String IEVersion = (userAgent.substring(userAgent.indexOf("rv")).split(" ")[0]).replace("rv:", "-");
            browser = "IE" + IEVersion.substring(0, IEVersion.length() - 1);
        } else {
            browser = "UnKnown, More-Info: " + userAgent;
        }
        return browser;
    }


    /**
     * 删除token前缀
     *
     * @param sourceToken 源token
     * @return 删除前缀后token
     */
    public static String removeTokenPrefix(String sourceToken) {
        if (!StrUtil.isBlank(sourceToken)) {
            sourceToken = sourceToken.replaceAll(AuthConstant.JWT_TOKEN_SUFFIX_KEY, "");
            sourceToken = sourceToken.replaceAll(AuthConstant.JWT_TOKEN_SUFFIX_KEY_2, "");
        }
        return sourceToken;
    }

    /**
     * 将字符串通过md5加密
     *
     * @param str 源字符串
     * @return md5加密后的字符串
     */
    public static String strMd5(String str) {
        if (StrUtil.isBlank(str))
            return null;
        return SecureUtil.md5(str);
    }

    /**
     * 将map转换成 url上需要的参数 比如 ?name=zs&age=19
     *
     * @param params
     * @return
     */
    public static String mapToUriParams(Map<String, String> params) {
        if (ObjectUtil.isEmpty(params))
            return "";
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        params.forEach((k, v) -> {
            sb.append(k);
            sb.append("=");
            sb.append(v);
            sb.append("&");
        });
        return sb.toString();
    }

    /**
     * 获取雪花id
     *
     * @return
     */
    public static Long getSnowFlakeId() {
        if (ObjectUtil.isEmpty(snowflake)) {
            snowflake = new Snowflake();
        }
        return snowflake.nextId();
    }

    /**
     * 获取List内重复的元素
     *
     * @param list
     * @return
     */
    public static List<String> getListRepeat(List<String> list) {
        return list.stream()
                .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum))
                .entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }
}
